package com.example.yiwei.crm.view.activity.JYCoordingActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetAreData;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.data.GetPeople;
import com.example.yiwei.crm.entity.BZFLEntity;
import com.example.yiwei.crm.entity.ClueMeesageEntity;
import com.example.yiwei.crm.entity.ContactMessageEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.entity.PeopleEntity;
import com.example.yiwei.crm.entity.dockingEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.json.YYSpinnerJson;
import com.example.yiwei.crm.util.HttpAssist;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.util.ZhengZhe;
import com.example.yiwei.crm.view.Class.listviewClass.CoorSelectAdapter;
import com.example.yiwei.crm.view.activity.areActivity.ProvinceActivity;
import com.example.yiwei.crm.view.activity.jtCustomer.JDcoorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static android.R.attr.gravity;


//协作简易版新增客户界面
public class AddCoorCustomerActivity extends BaseActivity {
    private EditText edit_name,edit_age,edit_mobile_phone,edit_id_card;
    private Button btn_show1;
    private TextView txt_birth_time;
    private RelativeLayout relativeLayout;
    private String pname,cname,aname,pid,cid,aid;
     private String pname1,cname1,aname1,pid1,cid1,aid1;
    private RadioGroup rg_sex;
    private RadioButton rb_men,rb_women;
    private ArrayAdapter adapter1,adapter2;
    private TextView txt_adress;
    private TimePickerView mpv;
    private TimePickerView mpv1;
    private String birth_time;
    Date date2;
    Date date1;
    List<managerEntity> managerList = new ArrayList<>();
    ClueMeesageEntity clue;
    private List<String> name_list=new ArrayList<>();
    List<dockingEntity> coorlist= new ArrayList<>();
    List<managerEntity> managerlist=new ArrayList<>();
    private List<String> coor_name_list = new ArrayList<>();
    private List<String> jd_name_list = new ArrayList<>();
    String managerName,result,disease_category;
    String coorname,jd_name;
    String birth1;
    int coor_id,jd_id;
    String today,today1;
    List<Map<String,String>> customerSpinner;
    int manager_id,sex,disease_category_id;
    List<String> client_list;
    List<CustomerMessageEntity> customerlist;
    CustomerMessageEntity customers;
    int birth;
    String manager_name_show,disease_category_show;
    private List<BZFLEntity> list6;
    SharedPreferences sp;
    List<BZFLEntity> disease_category_list;
    Button showbutton;
    int c=1;
    private EditText edit_bx;
    List<BZFLEntity> list;
    List<String> alist;
    List<String> qdly_list;
    String qdly;
    int qdly_id;
    private String ylname;
    private int ylid,fkid,hyid;
    private CustomerMessageEntity customer;
    private ContactMessageEntity contact;
    String sresult;
    int customer_id;
    ImageView im_comment;
    List<String> fk_list,hy_list;
    private ArrayAdapter adapter5,adapter6;
    TextView txt_title;
    Button button;
    private ImageView img_search,img_luru,img_me,img_tj,img_back;
    Button button1;
    private LinearLayout linearLayout1,linearLayout2,linearLayout3;
    private TextView txt1,txt2,txt3;
    private Spinner spinner_jd;
    private Spinner spinner_qdly;
    private ImageView img_qk,img_qk1;
    private ImageView img_coor_select;
    private PopupWindow mPopWindow;
    private EditText edit_search;
    private Button btn_search;
    private ListView listView;
    private CoorSelectAdapter adapter;
    private TextView show_coor;
    String KAA45,KAA46;
    String ImgPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_coor_customer);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        //清空文本框的文字
        img_qk= (ImageView) findViewById(R.id.qingkong);
        show_coor = (TextView) findViewById(R.id.show_coor_name);
        img_qk1= (ImageView) findViewById(R.id.qingkong1);
        txt_adress = (TextView) findViewById(R.id.customer_add_base_adress);
        spinner_qdly= (Spinner) findViewById(R.id.customer_add_channel_source);
        img_luru= (ImageView) findViewById(R.id.item_image_lr);
        txt_title = (TextView) findViewById(R.id.healt_education_add_txt_title);
        if ("update".equals(getIntent().getStringExtra("tag"))){
            txt_title.setText("修改患者信息");
        }
        //接待人的下拉列表
        spinner_jd= (Spinner) findViewById(R.id.customer_add_spinner_jdr);
        showbutton = (Button) findViewById(R.id.customer_add_base_adress_show);
        button1 = (Button) findViewById(R.id.add_customer_btn_xs);
        edit_id_card= (EditText) findViewById(R.id.customer_add_edit_idcard);
        img_search= (ImageView) findViewById(R.id.item_image_cx);
        img_back= (ImageView) findViewById(R.id.detailed_doc_img_back);
        img_me= (ImageView) findViewById(R.id.item_image_w);
        img_tj= (ImageView) findViewById(R.id.item_image_tj);
        //选择合作客户的图片
        img_coor_select = (ImageView) findViewById(R.id.img_xiangxia);
//        edit_bd = (EditText) findViewById(R.id.customer_add_edit_bd);
//        spinner_disease_category= (Spinner) findViewById(R.id.customer_add_spinner_disease_category);
        edit_age= (EditText) findViewById(R.id.customer_add_edit_age);
        edit_name= (EditText) findViewById(R.id.customer_add_edit_name);
        edit_mobile_phone= (EditText) findViewById(R.id.customer_add_edit_mobile_phone);
        btn_show1= (Button) findViewById(R.id.customer_add_btn_show1);
        txt_birth_time= (TextView) findViewById(R.id.customer_add_birth_time);
        rg_sex= (RadioGroup) findViewById(R.id.customer_add_rg_sex);
        rb_men= (RadioButton) findViewById(R.id.customer_add_rb_men);
        rb_women= (RadioButton) findViewById(R.id.customer_add_rb_women);
        relativeLayout= (RelativeLayout) findViewById(R.id.customer_add_relative_manager);
        //保险号的输入框
        edit_bx = (EditText) findViewById(R.id.userAdd_edit_security_numbers);
        button = (Button) findViewById(R.id.add_customer_btn);
        if("coor".equals(getIntent().getStringExtra("TAG"))){
            setSMMessage();
        }
        edit_id_card.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    if(!"".equals(edit_id_card.getText().toString())&&!ZhengZhe.idCard(edit_id_card.getText().toString())){
                        Toast.makeText(AddCoorCustomerActivity.this, "请填写正确的身份证号!", Toast.LENGTH_SHORT).show();
                    }else if (!"".equals(edit_id_card.getText().toString())){
                        String s = edit_id_card.getText().toString();
                        String year =s.substring(6,10);
                        String month = s.substring(10,12);
                        String day = s.substring(12,14);
                        if (Integer.parseInt(s.substring(16).substring(0, 1)) % 2 == 0){
                            rb_women.setChecked(true);
                            sex = 2;
                        }else {
                            rb_men.setChecked(true);
                            sex = 1;
                        }
                        Date date = new Date();// 得到当前的系统时间
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String fyear = format.format(date).substring(0, 4);// 当前年份
                        String fyue = format.format(date).substring(5, 7);// 月份
                        // String fday=format.format(date).substring(8,10);
                        int age = 0;
                        if (Integer.parseInt(month) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
                            age = Integer.parseInt(fyear) - Integer.parseInt(year);
                        } else {// 当前用户还没过生
                            age = Integer.parseInt(fyear) - Integer.parseInt(year)-1;
                        }
                        edit_age.setText(age+"");
                        txt_birth_time.setText(year+"-"+month+"-"+day);
                    }
                }
            }
        });

        Calendar calendar = Calendar.getInstance();
        //创建选择器
        mpv1 = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置时间范围
        Calendar calendar1 = Calendar.getInstance();
        mpv1.setRange(calendar.get(Calendar.YEAR) - 100, calendar1.get(Calendar.YEAR) + 100);
        //插入时间
        mpv1.setTime(new Date());
        //选择监听
        mpv1.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                birth_time=getTime(date);
                txt_birth_time.setText(birth_time);
            }
        });
        btn_show1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mpv1.show();
            }
        });
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        showbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddCoorCustomerActivity.this, ProvinceActivity.class);
                GetAreData.pname=null;
                GetAreData.aname = null;
                GetAreData.cname = null;
                GetAreData.pid = null;
                GetAreData.cid = null;
                GetAreData.aid = null;
                startActivity(intent);
            }
        });
        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorCustomerActivity.this, JDcoorActivity.class);
                intent.putExtra("ii","ii");
                startActivity(intent);
                finish();
            }
        });
        img_luru.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorCustomerActivity.this, JDcoorActivity.class);
                startActivity(intent);
                finish();
            }
        });
        img_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorCustomerActivity.this, JDcoorActivity.class);
                intent.putExtra("me","me");
                startActivity(intent);
                finish();
            }
        });
        img_tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorCustomerActivity.this, JDcoorActivity.class);
                intent.putExtra("tt","tt");
                startActivity(intent);
                finish();
            }
        });
        //清空显示出生日期的文本框
        img_qk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txt_birth_time.setText("");
            }
        });
        //清空显示所属区域的文本框
        img_qk1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txt_adress.setText("");
            }
        });
        //选择合作客户
        img_coor_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SC sc = new SC();
                        JSONObject object = sc.storage(sp);
                        String json = object.toString();
                        dockDao dockDao = new dockDaoImpl();
                        coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                               if (coorlist!=null){
                                   adapter = new CoorSelectAdapter(AddCoorCustomerActivity.this,coorlist);
                                   showPopupWindow();
                               }
                            }
                        });
                    }
                }).start();
            }
        });
        //修改时把之前新增选择的合作客户的名字赋值
        if ("update".equals(getIntent().getStringExtra("tag"))){
            customer = GetCustumer.get();
            show_coor.setText(customer.getCoor_name());
        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                SC sc = new SC();
//                JSONObject object = sc.storage(sp);
//                String json = object.toString();
//                dockDao dockDao = new dockDaoImpl();
//                coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (coorlist!=null){
//                            for (int i3 = 0;i3<coorlist.size();i3++){
//                                if (coorlist.get(i3).getDocking_mechanism()!=null&&!coorlist.get(i3).getDocking_mechanism().equals("")){
//                                    coor_name_list.add(coorlist.get(i3).getDocking_mechanism()+"-"+coorlist.get(i3).getDocking_name());
//                                }else{
//                                    coor_name_list.add(coorlist.get(i3).getDocking_name());
//                                }
//                            }
//                            adapter2 = new ArrayAdapter(AddCoorCustomerActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, coor_name_list);
//                            adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
//                            spinner_coor.setAdapter(adapter2);
//                            spinner_coor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                @Override
//                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                    coorname = coorlist.get(position).getDocking_name();
//                                    coor_id = coorlist.get(position).getDocking_id();
//                                    pname1=coorlist.get(position).getPname();
//                                    cname1=coorlist.get(position).getCname();
//                                    aname1=coorlist.get(position).getAname();
//                                    pid1=coorlist.get(position).getPid();
//                                    cid1=coorlist.get(position).getCid();
//                                    aid1=coorlist.get(position).getAid();
//                                }
//
//                                @Override
//                                public void onNothingSelected(AdapterView<?> parent) {
//
//                                }
//                            });
//                        }
//                        if ("update".equals(getIntent().getStringExtra("tag"))&&c==1){
//                            customer = GetCustumer.get();
//                            contact = GetContact.get();
//                            for (int i = 0;i<coorlist.size();i++){
//                                if (coorlist.get(i).getDocking_id()==customer.getCoor_id()){
//                                    spinner_coor.setSelection(i);
//                                }
//                            }
//                        }
//
//                    }
//                });
//            }
//        }).start();
//接待人的下拉列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                String json = object.toString();
                managerDao managerDao=new managerDaoImpl();
                managerList= managerDao.queryAllManager(baseClass.find_all_jd_url, json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        jd_name_list.add("");
                        if (managerList!=null){
                            for (int i3 = 0;i3<managerList.size();i3++){
                                jd_name_list.add(managerList.get(i3).getManager_name());
                            }
                            adapter1 = new ArrayAdapter(AddCoorCustomerActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, jd_name_list);
                            spinner_jd.setAdapter(adapter1);
                            spinner_jd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                    if (position>0){
                                        jd_name=managerList.get(position-1).getManager_name();
                                        jd_id=managerList.get(position-1).getManager_id();
                                    }

                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {

                                }
                            });
                        }
         //修改患者信息时把之前新增的接待人进行赋值
                        if ("update".equals(getIntent().getStringExtra("tag"))&&c==1){
                            customer = GetCustumer.get();
                            contact = GetContact.get();
                            for (int i = 0;i<managerList.size();i++){
                                if (managerList.get(i).getManager_id()==customer.getJd_id()){
                                    spinner_jd.setSelection(i+1);
                                }
                            }
                        }
                    }
                });
            }
        }).start();
        //渠道分类和渠道来源的下拉列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object2 = sc.storage(sp);
                try {
                    //渠道分类的id定为38取到渠道来源的值
                    object2.put("AKC01",38);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object2.toString();
                String result = NetWorkUtils.getCount(baseClass.find_QD_URL, json);
                list6 = YYSpinnerJson.getQDLY(result);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        qdly_list = new ArrayList<String>();
                        for (int i2=0;i2<list6.size();i2++){
                            qdly_list.add( list6.get(i2).getName());
                        }
                        adapter6 = new ArrayAdapter(AddCoorCustomerActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner,qdly_list);
                        adapter6.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        spinner_qdly.setAdapter(adapter6);
                        spinner_qdly.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                    qdly=list6.get(position).getName();
                                    qdly_id = list6.get(position).getId();
                            }
                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        if ("update".equals(getIntent().getStringExtra("tag"))){
                            customer = GetCustumer.get();
                            for (int i = 0;i<qdly_list.size();i++){
                                if (qdly_list.get(i).equals(customer.getChannel_source())){
                                    spinner_qdly.setSelection(i);
                                }
                            }
                        }
                    }
                });
            }
        }).start();

        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i==rb_men.getId()){
                    sex=1;
                }else{
                    sex=2;
                }
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            setMessage();
        }
//新增患者
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat    formatter2=new    SimpleDateFormat    ("MM-dd");
                SimpleDateFormat    formatter1=new    SimpleDateFormat    ("yyyy");
                Date    curDate=new    Date(System.currentTimeMillis());//获取当前时间
                today =formatter2.format(curDate);
                today1=formatter1.format(curDate);
                //新增客户如果不选择出生日期用今天时间减去年龄算出大概的日期
                if (!"".equals(edit_age.getText().toString())&&!"".equals(today1)){
                    birth=Integer.valueOf(today1)-Integer.valueOf(edit_age.getText().toString());
                }
                birth1=birth+"-"+today;
                String a = getTime(new Date());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                boolean b = ZhengZhe.idCard(edit_id_card.getText().toString());
                try {
                    date2 =  formatter.parse(a);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //新增患者的必填项的判断
                if ("".equals(edit_name.getText().toString())||"".equals(edit_age.getText().toString())||0==sex) {
                    Toast.makeText(AddCoorCustomerActivity.this, "请填写必填项!", Toast.LENGTH_SHORT).show();
                }else if(!"".equals(edit_mobile_phone.getText().toString())&&!ZhengZhe.phone(edit_mobile_phone.getText().toString())){
                        Toast.makeText(AddCoorCustomerActivity.this, "请输入正确的手机号码!", Toast.LENGTH_SHORT).show();
                    }
                   else if(!"".equals(edit_id_card.getText().toString())&&!b){
                        Toast.makeText(AddCoorCustomerActivity.this, "请填写正确的身份证号!", Toast.LENGTH_SHORT).show();
                    }else if ("".equals(show_coor.getText().toString())){
                    Toast.makeText(AddCoorCustomerActivity.this, "请选择合作客户", Toast.LENGTH_SHORT).show();
                }
               else {
                        button.setVisibility(View.GONE);
                    if ("saomiao".equals(getIntent().getStringExtra("ly"))){
                        uploadImg();
                    }else {
                        add();
                    }
                }
            }
        });
        //选择显示和隐藏页面的一些信息
        inity();
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (linearLayout1.getVisibility()==View.GONE){

                    initx();
                    button1.setText("点击隐藏");
                }else {
                    inity();
                    button1.setText("点击显示");
                }
            }
        });
    }

    public void uploadImg(){
        Toast.makeText(AddCoorCustomerActivity.this, "信息正在上传请稍候！！", Toast.LENGTH_SHORT).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(ImgPath);
                if (file.exists()){
                    Log.d("ccc",file.getName());
                    String URL=baseClass.upload_img_URL+"?type=KAA1&UAB02="+sp.getString("UAB02",null)+"&KAA07="+edit_id_card.getText().toString();
                    Log.d("cccc",sp.getString("UAB02",null)+"?KAA07="+edit_id_card.getText().toString());
                    final String s = HttpAssist.uploadFile(file,URL);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Log.d("aaa",s);
                                JSONObject object = new JSONObject(s);
                                boolean b = object.getBoolean("ifsuccess");
                                if (b){
                                    JSONObject object2 = object.getJSONObject("list");
                                    KAA45 = object2.getString("KAA45");
                                    KAA46 = object2.getString("KAA46");
                                    add();
                                }else {
                                    button.setVisibility(View.VISIBLE);
                                    Toast.makeText(AddCoorCustomerActivity.this, "照片上传失败！！请重试", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }).start();
    }
    private void setSMMessage() {
        PeopleEntity peo = GetPeople.getpeople();
        if (peo!=null){
            edit_name.setText(peo.getName());
            String bd = peo.getBirthday();
            txt_birth_time.setText(bd.substring(0,4)+"-"+bd.substring(4,6)+"-"+bd.substring(6,8));
            edit_id_card.setText(peo.getIdcard());
            if ("男".equals(peo.getSex())) {
                rb_men.setChecked(true);
            } else if ("女".equals(peo.getSex())) {
                rb_women.setChecked(true);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
            String s = format.format(new Date());
            edit_age.setText(Integer.valueOf(s.substring(0,4))-Integer.valueOf(bd.substring(0,4))+"");
            ImgPath = peo.getPath();
//        Log.d("cc",Integer.valueOf(s.substring(0,4))+"-"+Integer.valueOf(bd.substring(0,4)));
            GetPeople.peopleEntity=null;
        }
    }

    //修改时赋值
    public void setMessage(){
        customer = GetCustumer.get();
        contact = GetContact.get();
        edit_name.setText(customer.getClient_name());
        edit_id_card.setText(customer.getIDNumber());

        edit_age.setText(customer.getClient_age()+"");
        txt_birth_time.setText(customer.getBirthDay());

        txt_adress.setText(customer.getPname()+customer.getCname()+customer.getAname());

        edit_mobile_phone.setText(contact.getFirst_contact_mobile_phone());
        if (customer.getClient_gender() != 0) {
            if (customer.getClient_gender() == 1) {
                rb_men.setChecked(true);
            } else if (customer.getClient_gender() == 2) {
                rb_women.setChecked(true);
            }
        }
        edit_bx.setText(customer.getSecurity_numbers());
    }
//新增患者
    private void add() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();

                JSONObject json = sc.storage(sp);

                try {
                    json.put("KAA02", edit_name.getText().toString());
                    json.put("KAA03", edit_age.getText().toString());
                    if (rb_men.isChecked()) {
                        json.put("KAA04", 1);
                    } else if (rb_women.isChecked()) {
                        json.put("KAA04", 2);
                    }

                    json.put("KAA07", edit_id_card.getText().toString());

                    json.put("KXA01",coor_id);

                    if ("update".equals(getIntent().getStringExtra("tag"))) {
                        json.put("addoredit", "edit");
                        json.put("OKAA39",customer.getJd_id());
                        json.put("OKAA40",customer.getJd());
                        json.put("KAA01", customer.getClient_id());
                        json.put("KXA01",customer.getCoor_id());
                        json.put("KLA01",contact.getContact_id());
                    } else {
                        if ("kehuchi".equals(getIntent().getStringExtra("kehuchiTag"))) {
                            json.put("KAA09", 0);
                        } else {
                            json.put("KAA09", sp.getString("CID01",null));
                            json.put("KAA09A", sp.getString("CID03",null));
                        }
                        json.put("addoredit", "add");
                    }
                    if (pid != null) {
                        json.put("KAA23", Integer.valueOf(pid));
                        json.put("KAA24", Integer.valueOf(cid));
                        json.put("KAA25", Integer.valueOf(aid));
                        json.put("KAA30", pname);
                        json.put("KAA31", cname);
                        json.put("KAA32", aname);
                    }else{
                        if (pid1!=null){
                            json.put("KAA23", Integer.valueOf(pid1));
                            json.put("KAA24", Integer.valueOf(cid1));
                            json.put("KAA25", Integer.valueOf(aid1));
                            json.put("KAA30", pname1);
                            json.put("KAA31", cname1);
                            json.put("KAA32", aname1);
                        }
                    }
                    if ("".equals(txt_birth_time.getText().toString())){
                        json.put("KAA05", birth1);
                    }else{
                        json.put("KAA05", txt_birth_time.getText().toString());
                    }
                    json.put("KLA06", edit_mobile_phone.getText().toString());
                    json.put("CID03", sp.getString("CID03", null));
                    json.put("KLA14", 1);
                    json.put("KAA12",edit_bx.getText().toString());
                    if (0==jd_id){

                    }else{
                        json.put("KAA39",jd_id);
                    }
                    json.put("AKC01",38);
                    json.put("AKD01",qdly_id);
                    json.put("KLA02",edit_name.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String sjson = json.toString();
                sresult = NetWorkUtils.getCount(baseClass.add_coor_customer_URL, sjson);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (sresult != null) {
                            try {
                                final JSONObject object = new JSONObject(sresult);
                                boolean b = object.getBoolean("ifsuccess");
                                if (b) {
                                    boolean c = object.getBoolean("only");
                                    if (c) {
                                        if ("update".equals(getIntent().getStringExtra("tag"))) {
                                            Toast.makeText(AddCoorCustomerActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        } else {
                                            Toast.makeText(AddCoorCustomerActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                        }
                                        if ("update".equals(getIntent().getStringExtra("tag"))) {

                                        } else {
                                            AlertDialog.Builder builder;
                                            builder = new AlertDialog.Builder(new ContextThemeWrapper(AddCoorCustomerActivity.this, R.style.custom_dialog));
                                            builder.setTitle("是否要跳转到预约界面？");
                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    Intent intent = new Intent(AddCoorCustomerActivity.this, JYAddApoActivity.class);
                                                    try {
                                                        //跳转到预约界面将输入的客户信息显示到预约界面
                                                        int customerid = object.getInt("KAA01");
                                                        intent.putExtra("tag", "add");
                                                        intent.putExtra("KAA01", customerid);
                                                        intent.putExtra("qdfl_id", 38);
                                                        intent.putExtra("qdfl", "学术协作");
                                                        intent.putExtra("qdly_id", qdly_id);
                                                        intent.putExtra("qdly", qdly);
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                    startActivity(intent);
                                                    finish();
                                                }
                                            });
                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    finish();
                                                }
                                            });
                                            builder.setCancelable(false);
                                            builder.show();
                                        }

                                    } else {
                                        final int customerid = object.getInt("KAA01");
                                        final AlertDialog.Builder builder2;
                                        builder2 = new AlertDialog.Builder(new ContextThemeWrapper(AddCoorCustomerActivity.this, R.style.custom_dialog));
                                        builder2.setTitle("该客户已存在，是否变为追加负责人？");
                                        builder2.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        final JSONObject object = new JSONObject();
                                                        try {
                                                            object.put("KAA09", sp.getString("UAB01",null));
                                                            object.put("KAA01", customerid);
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                        String json = object.toString();
                                                        final String result = NetWorkUtils.getCount(baseClass.zj_manger_url, json);
                                                        Log.d("aaa", result);
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                try {
                                                                    JSONObject object1 = new JSONObject(result);
                                                                    boolean d = object1.getBoolean("ifsuccess");
                                                                    if (d) {
                                                                        if ("update".equals(getIntent().getStringExtra("tag"))) {
                                                                            finish();
                                                                        } else {
                                                                            AlertDialog.Builder builder;
                                                                            builder = new AlertDialog.Builder(new ContextThemeWrapper(AddCoorCustomerActivity.this, R.style.custom_dialog));
                                                                            builder.setTitle("是否要跳转到预约界面？");
                                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                                @Override
                                                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                                                    Intent intent = new Intent(AddCoorCustomerActivity.this, JYAddApoActivity.class);
                                                                                    try {
                                                                                        //跳转到预约界面将输入的客户信息显示到预约界面
                                                                                        int customerid = object.getInt("KAA01");
                                                                                        intent.putExtra("tag", "add");
                                                                                        intent.putExtra("KAA01", customerid);
                                                                                        intent.putExtra("qdfl_id", 38);
                                                                                        intent.putExtra("qdfl", "学术协作");
                                                                                        intent.putExtra("qdly_id", qdly_id);
                                                                                        intent.putExtra("qdly", qdly);
                                                                                    } catch (JSONException e) {
                                                                                        e.printStackTrace();
                                                                                    }
                                                                                    startActivity(intent);
                                                                                    finish();
                                                                                }
                                                                            });
                                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                                @Override
                                                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                                                    finish();
                                                                                }
                                                                            });
                                                                            builder.show();
                                                                        }
                                                                    }
                                                                } catch (JSONException e) {
                                                                    e.printStackTrace();
                                                                }

                                                            }
                                                        });

                                                    }
                                                }).start();

                                            }
                                        });
                                        builder2.setNegativeButton("否", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                button.setVisibility(View.VISIBLE);

                                            }
                                        });
                                        builder2.setCancelable(false);
                                        builder2.show();
                                    }
                                }else {
                                    button.setVisibility(View.VISIBLE);
                                        if ("update".equals(getIntent().getStringExtra("tag"))) {
                                            Toast.makeText(AddCoorCustomerActivity.this, "修改失败，请重试！！", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(AddCoorCustomerActivity.this, "添加失败，请重试！！", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
//返回页面的刷新方法
    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetAreData.pname!=null){
            pid = GetAreData.pid;
            pname = GetAreData.pname;
            cid = GetAreData.cid;
            cname = GetAreData.cname;
            aid = GetAreData.aid;
            aname =GetAreData.aname;
            txt_adress.setText(pname+cname+aname);
        }
    }
    //点击隐藏和显示
    private void inity() {
        linearLayout1= (LinearLayout) findViewById(R.id.linear_id_card);
        linearLayout1.setVisibility(View.GONE);
        linearLayout2= (LinearLayout) findViewById(R.id.linear_birth_time);
        linearLayout2.setVisibility(View.GONE);
        linearLayout3= (LinearLayout) findViewById(R.id.linear_address);
        linearLayout3.setVisibility(View.GONE);
        txt1= (TextView) findViewById(R.id.txt1);
        txt1.setVisibility(View.GONE);
        txt2= (TextView) findViewById(R.id.txt2);
        txt2.setVisibility(View.GONE);
        txt3= (TextView) findViewById(R.id.txt3);
        txt3.setVisibility(View.GONE);

    }
    private void initx(){
        linearLayout1.setVisibility(View.VISIBLE);
        linearLayout2.setVisibility(View.VISIBLE);
        linearLayout3.setVisibility(View.VISIBLE);
        txt1.setVisibility(View.VISIBLE);
        txt2.setVisibility(View.VISIBLE);
        txt3.setVisibility(View.VISIBLE);
    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(AddCoorCustomerActivity.this).inflate(
                R.layout.popuwindoe_select_coor, null);
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height=LinearLayout.LayoutParams.WRAP_CONTENT;
        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(width);
        mPopWindow.setHeight(height);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();    //  获取测量后的宽度
        final int popupHeight = contentView.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        edit_search = (EditText) contentView.findViewById(R.id.edit_seacher);
        btn_search = (Button) contentView.findViewById(R.id.btn_show);
        listView = (ListView) contentView.findViewById(R.id.btn_listview);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                coorname = coorlist.get(position).getDocking_name();
                coor_id = coorlist.get(position).getDocking_id();
                show_coor.setText(coorname);
//                mPopWindow.setOnDismissListener(new poponDismissListener());
                mPopWindow.dismiss();
            }
        });
        //搜索合作客户
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SC sc = new SC();
                        JSONObject object = sc.storage(sp);
                        try {
                            object.put("KXA02",edit_search.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String json = object.toString();
                        dockDao dockDao = new dockDaoImpl();
                        coorlist = dockDao.queryAllCoordinationMessage(baseClass.find_coordination_url + 1, json);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (coorlist==null){
                                    Toast.makeText(AddCoorCustomerActivity.this, "搜索不到信息！！", Toast.LENGTH_SHORT).show();
                                }else {
                                    adapter = new CoorSelectAdapter(AddCoorCustomerActivity.this,coorlist);
                                    listView.setAdapter(adapter);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                }).start();
            }
        });
        img_coor_select.getLocationOnScreen(location);
        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
        mPopWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.pop_bg));

        mPopWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        mPopWindow.setFocusable(true);
        mPopWindow.update();
        backgroundAlpha(0.5f);
        mPopWindow.showAsDropDown(img_coor_select);
        mPopWindow.setOnDismissListener(new poponDismissListener());
        mPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
//        if (mPopWindow.isShowing()){
//            mPopWindow.dismiss();
//        }else{
//            mPopWindow.isShowing();
//        }
    }
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha= bgAlpha;
        getWindow().setAttributes(lp);
    }
    class poponDismissListener implements PopupWindow.OnDismissListener{

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }

    }
}
